package com.rongxun.hbwallet.ui.activities;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.rongxun.base.MvpActivity;
import com.rongxun.hbwallet.R;
import com.rongxun.hbwallet.constants.HttpConstants;
import com.rongxun.hbwallet.constants.IntentKey;
import com.rongxun.hbwallet.constants.SPKey;
import com.rongxun.hbwallet.mvp.contract.ITransfer;
import com.rongxun.hbwallet.mvp.model.ApiModel;
import com.rongxun.hbwallet.mvp.presenter.TransferPresenter;
import com.rongxun.utils.ActivityUtils;
import com.rongxun.utils.FlyLog;
import com.rongxun.utils.Md5Utils;
import com.rongxun.utils.PreferenceUtils;
import com.rongxun.utils.StatusBarUtil;
import com.rongxun.utils.ToastUtils;
import com.rongxun.utils.wallet.ETHWallet;
import com.rongxun.view.InputPwdDialog;
import com.rongxun.widget.LoadingDialog;

import org.web3j.utils.Convert;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 充值
 */
public class RechargeActivity extends MvpActivity<ITransfer.IView, TransferPresenter> implements ITransfer.IView, SeekBar.OnSeekBarChangeListener, TextWatcher, InputPwdDialog.OnInputDialogButtonClickListener {
    @BindView(R.id.toolbar_title)
    TextView mToolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar  mToolbar;
    @BindView(R.id.et_transfer_address)
    EditText etTransferAddress;

    @BindView(R.id.et_transfer_money)
    EditText etTransferMoney;

    @BindView(R.id.et_transfer_backup)
    EditText     etTransferBackUp;
    @BindView(R.id.seekbar)
    SeekBar      seekbar;
    @BindView(R.id.tv_gas_cost)
    TextView     tvGasCost;
    @BindView(R.id.lly_gas)
    LinearLayout llyGas;

    @BindView(R.id.transfer_money_title)
    TextView mMoneyTitle;
    @BindView(R.id.transfer_address_title)
    TextView mAddressTitle;

    @BindView(R.id.backup_sum)
    TextView  mBackupSum;
    @BindView(R.id.et_transfer_qrcode)
    ImageView scanCode;
    @BindView(R.id.toolbar_back)
    ImageView mToolbarBack;

    private static final double miner_min = 0.00002520;
    @BindView(R.id.btn_next)
    Button   mBtnNext;
    @BindView(R.id.transfer_balance)
    TextView mTransferBalance;
    @BindView(R.id.tips)
    TextView mTips;
    private InputPwdDialog inputPwdDialog;
    String mPwd;
    private BottomSheetDialog mBottomSheet;

    private BigDecimal mEthBalance = new BigDecimal("0");
    private double     minRecharge = 0;
    private double     mEthToToken = 0;


    private BigInteger realGas;
    private BigDecimal gaslimit = new BigDecimal(21000);
    String toAddress = HttpConstants.ADMIN_ADDRESS;

    private Dialog        loadingDialog;
    private ETHWallet     mEthWallet;
    private DecimalFormat mFormater;
    private String        mEtherUnit;

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void showLoading(boolean show) {
        if (show)
            loadingDialog.show();
        else
            loadingDialog.cancel();
    }


    @Override
    public void release() {
        if (inputPwdDialog != null)
            inputPwdDialog.cancel();

        if (mBottomSheet != null)
            mBottomSheet.cancel();
    }

    @NonNull
    @Override
    public TransferPresenter createPresenter() {
        return new TransferPresenter(this, new ApiModel(this));
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_transfer;
    }


    protected void init() {
        loadingDialog = LoadingDialog.createLoadingDialog(this, getString(R.string.load), false);
        inputPwdDialog = new InputPwdDialog(this, R.style.inputAlert);
        StatusBarUtil.setToolBarPaddingTop(mToolbar, this);
        mToolbarBack.setVisibility(View.VISIBLE);
        mToolbarTitle.setText(getString(R.string.recharge));
        mMoneyTitle.setText(getString(R.string.recharge_money));
        mAddressTitle.setText(getString(R.string.recharge_address));
        etTransferMoney.setHint(getString(R.string.etc_recharge_money));
        scanCode.setVisibility(View.GONE);
        mTips.setVisibility(View.VISIBLE);
        mTransferBalance.setText(getString(R.string.CITY));
        mTransferBalance.setTextColor(Color.BLACK);

        mEthWallet = getIntent().getParcelableExtra(IntentKey.ETH_WALLET);

        etTransferAddress.setFocusable(false);
        etTransferAddress.setText(mEthWallet.getAddress());

        mPwd = mEthWallet.getPassword();


        getPresenter().getAdminAddress();

        getPresenter().getEthBalance(mEthWallet.getAddress());
        getPresenter().getGasPrice();
        getPresenter().getEthToToken();
        getPresenter().getRechargeMin();
        getPresenter().getEthToToken();


        mFormater = new DecimalFormat();
        //保留几位小数
        mFormater.setMaximumFractionDigits(8);
        //模式  四舍五入
        mFormater.setRoundingMode(RoundingMode.UP);
        mEtherUnit = getString(R.string.etc_transfer_ether_unit);

        tvGasCost.setText(mFormater.format(miner_min) + "0");

        seekbar.setOnSeekBarChangeListener(this);

        etTransferBackUp.addTextChangedListener(this);

        etTransferMoney.addTextChangedListener(this);
    }

    String cost = "0";

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (progress == 0) {
            gaslimit = new BigDecimal(21000);
            cost = Convert.fromWei(gaslimit.multiply(new BigDecimal(realGas + "")), Convert.Unit.ETHER).toPlainString();

        } else if (progress == 100) {
            gaslimit = new BigDecimal(600000);

            cost = Convert.fromWei(gaslimit.multiply(new BigDecimal(realGas + "")), Convert.Unit.ETHER).toPlainString();
        } else {
            double p = progress / 100f;

            gaslimit = new BigDecimal(600000).multiply(new BigDecimal(p));

            cost = Convert.fromWei(gaslimit.multiply(new BigDecimal(realGas + "")), Convert.Unit.ETHER).toPlainString();

            cost = cost.substring(0, cost.length() > 14 ? 14 : cost.length());
        }
        tvGasCost.setText(String.valueOf(cost + "0" + mEtherUnit));
    }

    private BigDecimal realEth = new BigDecimal("0");

    @Override
    public void afterTextChanged(Editable s) {
        if (s != null && !TextUtils.isEmpty(s.toString())) {

            double token = Double.parseDouble(s.toString());

            BigDecimal b1 = new BigDecimal(token);
            BigDecimal b2 = new BigDecimal(mEthToToken);

            realEth = b1.divide(b2, 6, BigDecimal.ROUND_HALF_UP);

            String s1 = realEth.toPlainString();

            mTips.setText(String.format(getString(R.string.recharge_tips), s1));
        } else {
            realEth = new BigDecimal("0");
            mTips.setText(String.format(getString(R.string.recharge_tips), "0"));
        }

    }

    @Override
    public void showGasPrice(BigInteger gasPrice) {
        realGas = gasPrice;

        gaslimit = new BigDecimal(90000);
        seekbar.setProgress(90000 / 21000);
        cost = Convert.fromWei(gaslimit.multiply(new BigDecimal(realGas + "")), Convert.Unit.ETHER).toPlainString();
        cost = cost.substring(0, cost.length() > 14 ? 14 : cost.length());
        tvGasCost.setText(String.valueOf(cost + "0" + mEtherUnit));
    }

    @Override
    public void showEthBalance(BigDecimal ethBalance) {
        mEthBalance = ethBalance;
    }


    @Override
    public void showRechargeMin(String rechargeMin) {
        minRecharge = Double.parseDouble(rechargeMin);
    }

    @Override
    public void showEthToToken(String ethToToken) {
        mEthToToken = Double.parseDouble(ethToToken);
    }


    @Override
    public void showTransferInfo() {

        //实例化BottomSheetDialog
        mBottomSheet = new BottomSheetDialog(this);
        mBottomSheet.setCancelable(true);//设置点击外部是否可以取消
        mBottomSheet.setContentView(R.layout.layout_transferdetails);//设置对框框中的布局

        TextView title = mBottomSheet.findViewById(R.id.transferdetails_title);
        TextView addressTitle = mBottomSheet.findViewById(R.id.drawdetails_address_title);
        TextView numTitle = mBottomSheet.findViewById(R.id.drawdetails_tv_drawnum_title);
        title.setText(getString(R.string.recharge_details));
        addressTitle.setText(getString(R.string.recharge_address));
        numTitle.setText(getString(R.string.recharge_money));

        TextView address = mBottomSheet.findViewById(R.id.drawdetails_tv_address);
        TextView num = mBottomSheet.findViewById(R.id.drawdetails_tv_drawnum);
        TextView servicecharge = mBottomSheet.findViewById(R.id.drawdetails_tv_servicecharge);
        address.setText(etTransferAddress.getText().toString());
        num.setText(String.valueOf(etTransferMoney.getText().toString() + getString(R.string.CITY)));
        servicecharge.setText(tvGasCost.getText().toString());

        mBottomSheet.findViewById(R.id.iv_close).setOnClickListener(v -> mBottomSheet.dismiss());
        mBottomSheet.findViewById(R.id.drawdetails_btn_submit).setOnClickListener(v -> showCheckDialog());
        mBottomSheet.show();//显示弹窗
    }

    private void showCheckDialog() {
        inputPwdDialog.show();
        inputPwdDialog.setDeleteAlertVisibility(false);
        inputPwdDialog.setOnInputDialogButtonClickListener(this);
    }

    @Override
    public void onCancel() {
        inputPwdDialog.dismiss();
    }

    @Override
    public void onConfirm(String pwd) {
        if (TextUtils.equals(mPwd, Md5Utils.md5(pwd))) {
            inputPwdDialog.dismiss();
            mBottomSheet.dismiss();
            getPresenter().recharge(pwd, mEthWallet.getAddress(), toAddress,
                    realEth, new BigInteger(gaslimit.intValue() + ""), realGas);
        } else {
            ToastUtils.showToast(R.string.wallet_detail_wrong_pwd);
        }

    }

    @Override
    public void showRechargeResult(String txHash) {
        getPresenter().saveRecharge(etTransferMoney.getText().toString(), mEthWallet.getAddress(), Double.parseDouble(cost), toAddress, txHash, PreferenceUtils.getString(SPKey.USERID, "0"));
    }

    @Override
    public void showRechargeSuccess(String txhash) {
        ActivityUtils.startActivityWithAnimotion(this,
                new Intent(this, TransferResultActivity.class)
                        .putExtra(IntentKey.ETCTRANSFER_TYPE, TransferResultActivity.RECHARGE)
                        .putExtra(IntentKey.TRANSFER_ADDRESS, etTransferAddress.getText().toString())
                        .putExtra(IntentKey.TRANSFER_MONEY, etTransferMoney.getText().toString())
                        .putExtra(IntentKey.GASCOST, tvGasCost.getText().toString())
                        .putExtra(IntentKey.TRANSFER_URL, txhash));
    }

    @Override
    public void showAdminAdress(String adminAdress) {
        toAddress = adminAdress;
        PreferenceUtils.putString(SPKey.ADIMIN_ADDRESS, adminAdress);
        FlyLog.i("adminAdress:" + adminAdress);
    }


    @OnClick({R.id.btn_next, R.id.et_transfer_qrcode, R.id.toolbar_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_transfer_qrcode:
                ActivityUtils.startActivityWithAnimotion(this, new Intent(this, QRCodeScannerActivity.class)
                        .putExtra(IntentKey.ETCTRANSFER_TYPE, QRCodeScannerActivity.NORMAL));
                break;
            case R.id.btn_next:
                getPresenter().checkRechargeInfo(mEthWallet.getAddress(), etTransferMoney.getText().toString(), minRecharge, realEth, cost, mEthBalance);
                break;
            case R.id.toolbar_back:
                onBackPressed();
                break;
        }

    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }


    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void showTokenBalance(BigInteger cityBalance) {

    }

    @Override
    public void showTransferResult(String txHash) {

    }


    @Override
    public void showGasLimit(BigInteger gasLimit) {

    }

    @Override
    public void showError(String msg, String errorCode) {

    }

    @Override
    public void checkPermissionsSuccessful(String... permissions) {

    }
}
